﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;

namespace MadProps.Validation
{
    public class ValidationModel : INotifyPropertyChanged
    {
        readonly IProp prop;
        readonly IValidator validator;

        public ValidationModel(IProp prop, IValidator validator)
        {
            this.prop = prop.ThrowIfNull("prop");
            this.validator = validator.ThrowIfNull("validator");

            prop.PropChanged += prop_PropChanged;
        }

        void prop_PropChanged(object sender, PropChangedEventArgs e)
        {
            var args = new ValidationArgs(prop);
            var result = validator.Validate(args);

            this.IsValid = result.IsValid;
            this.Message = result.Messages.EmptyIfNull().FirstOrDefault();
        }

        private bool isValid;
        public bool IsValid
        {
            get
            {
                return this.isValid;
            }
            set
            {
                if (this.isValid != value)
                {
                    this.isValid = value;
                    this.PropertyChanged.Raise(this, "IsValid");
                }
            }
        }

        private string message;
        public string Message
        {
            get
            {
                return this.message;
            }
            set
            {
                if (this.message != value)
                {
                    this.message = value;
                    this.PropertyChanged.Raise(this, "Message");
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }
}
